#include "conversationdelegate.h"

#include "conversationmodel.h"
#include <QPainter>
#include <QBrush>
#include <QtDebug>

#define WIDTH_OFFSET 50

ConversationDelegate::ConversationDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{

}

ConversationDelegate::~ConversationDelegate() {

}

void ConversationDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    if (index.isValid()) {
        int color = index.data(ConversationModel::Role::Color).toInt();
        bool myMsg = index.data(ConversationModel::Role::MyMsg).toBool();
        QString content = index.data(ConversationModel::Role::Content).toString();
        QRect rect = option.rect;
        rect.setWidth(rect.width() - WIDTH_OFFSET);
        if (myMsg) {
            rect.moveLeft(rect.left() + WIDTH_OFFSET);
        }

        painter->save();
        painter->setPen(QColor(color));
        painter->setBrush(QBrush(QColor(color)));
        painter->drawRoundedRect(rect, 3, 3);
        painter->restore();

        painter->save();
        painter->drawText(rect, Qt::AlignLeft, content);
        painter->restore();
    }
}

QSize ConversationDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const {
    if (index.isValid()) {
        QString content = index.data(ConversationModel::Role::Content).toString();

        QRect r = option.fontMetrics.boundingRect(
                    0, 0, option.rect.width() - WIDTH_OFFSET, option.rect.height(),
                    Qt::AlignLeft, content);
        r.setWidth(option.rect.width());

        return r.size();
    }

    return QSize(0, 0);
}
